<template>
  <div>
    <el-dropdown v-if="!isLogin" @command="handleCommand">
      <span class="el-dropdown-link" style="font-size: 18px; cursor: pointer;">
        <i class="el-icon-user"></i>
        {{ userNameDisplay }}
        <i class="el-icon-arrow-down el-icon--right"></i>
      </span>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item command="login">登录</el-dropdown-item>
        <el-dropdown-item command="register">注册</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
    <el-dropdown v-else @command="handleCommand">
      <span class="el-dropdown-link" style="font-size: 18px; cursor: pointer;">
        <i class="el-icon-user"></i>
        {{ userNameDisplay }}
        <i class="el-icon-arrow-down el-icon--right"></i>
      </span>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item command="logout">登出</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
export default {
  name: 'UserMenu',
  computed: {
    ...mapGetters(['userInfo']),
    isLogin() {
      return !!this.userInfo && !!this.userInfo.name
    },
    userNameDisplay() {
      return this.isLogin ? this.userInfo.name : '未登录'
    }
  },
  methods: {
    ...mapActions(['logoutAct']),
    handleCommand(command) {
      if (command === 'login') {
        window.location.href = '/login'
      } else if (command === 'register') {
        window.location.href = '/login?page=register'
      } else if (command === 'logout') {
        this.logoutAct().then(() => {
          window.location.href = '/login'
        })
      }
    }
  }
}
</script>

<style scoped>
.el-dropdown-link {
  outline: none;
}
</style>